library(plyr)
library(igraph)
library(RgoogleMaps)
library(RColorBrewer)
library(fmsb)
library(tidyverse)
library(multcomp)

setwd("~/Dropbox/China Huawei Paper/Production Materials/Replication/")
dat <- read.csv("dataFile_China_Huawei.csv")

dat$autocracy <- NA
dat$autocracy[dat$v2x_polyarchy>0.42] <- 0
dat$autocracy[dat$v2x_polyarchy<=0.42] <- 1


#################################
# 		Leading Countries		#
#################################

who = ddply(dat[dat$year>=2000 & dat$year<=2021,], .(cabb, year), plyr::summarize, huawei=sum(china.huawei,na.rm=T), v2x_polyarchy=mean(v2x_polyarchy,na.rm=T), autocracy=mean(autocracy,na.rm=T))
who$huawei[is.na(who$huawei)==T] <- 0 
who <- who[who$huawei>0,]

who.cabb = ddply(who, .(autocracy,cabb), plyr::summarize, huawei=sum(huawei,na.rm=T)/1000000, v2x_polyarchy=mean(v2x_polyarchy,na.rm=T))

who.cabb <- who.cabb[order(who.cabb$huawei, decreasing=T),]
colors <- c("black","gray")
who.cabb$color[who.cabb$autocracy==1] <- colors[1]
who.cabb$color[who.cabb$autocracy==0] <- colors[2]

names <- c("Indonesia", "Uzbekistan", "Cameroon", "Costa Rica", "Chad", "DR Congo", "Cote d'Ivoire", "Bolivia", "Ethiopia", "Tunisia", "Burundi", "Ukraine", "Malawi", "Moldova", "Pakistan", "Algeria", "Angola", "Pakistan"," Venezuela", "Tajikistan", "Gambia", "Gambia", "Ghana", "Guinea")

num <- length(who.cabb$huawei[who.cabb$huawei]>=1)
unit <- 1

who.cabb$huawei[(num+1):length(who.cabb$huawei)]

par(mar=c(bottom=8.5, left=4.5, top=1.1, right=1), bg=NA)
barplot(height=who.cabb$huawei[1:num]/unit, space=0.05, beside=FALSE, axes=F, border=FALSE, col=who.cabb$color[1:num], bg=NA, col.axis="Black", cex.axis=1.3, cex.names=1.3, ylim=c(0,max(who.cabb$huawei[1:num])/unit), names.arg=names[1:num], las=2, main="Leading Countries", cex.main=1.54)
axis(2, at=seq(from=0, to=max(who.cabb$huawei[1:num])/unit, by=50), las=2, tick = T, cex.axis=1.3, col="Black", col.ticks="Black", col.axis="Black")
mtext("Total Commitments (in Millions USD)", side=2, line=3.4, col="Black", cex=1.3)
legend(x="topright", legend=c("Autocracy","Democracy"), fill=colors, border=colors, cex=1.3, box.col=NA, bg=NA, text.col="Black")


#################################
# 		Transfers Over Time		#
#################################

when = ddply(dat[dat$year>=2000 & dat$year<=2017,], .(year,autocracy), plyr::summarize, huawei=sum(china.huawei,na.rm=T))
when.auts <- when[when$autocracy==1,]; when.auts$huawei.cum <- NA; for(i in 1:nrow(when.auts)){when.auts$huawei.cum[i]<-sum(when.auts$huawei.cum[i-1], when.auts$huawei[i], na.rm=T)}
when.dems <- when[when$autocracy==0,]; when.dems$huawei.cum <- NA; for(i in 1:nrow(when.dems)){when.dems$huawei.cum[i]<-sum(when.dems$huawei.cum[i-1], when.dems$huawei[i], na.rm=T)}
when.ins = ddply(dat[dat$year>=2000 & dat$year<=2017 & dat$cabb!="INS",], .(year,autocracy), plyr::summarize, huawei=sum(china.huawei,na.rm=T))
when.dems.ins <- when.ins[when.ins$autocracy==0,]; when.dems.ins$huawei.cum <- NA; for(i in 1:nrow(when.dems.ins)){when.dems.ins$huawei.cum[i]<-sum(when.dems.ins$huawei.cum[i-1], when.dems.ins$huawei[i], na.rm=T)}

unit <- 1000000

par(mar=c(bottom=3, left=4.1, top=1.1, right=1), bg=NA)
plot(when.auts$year, when.auts$huawei.cum/unit, bty="n", type="l", lty=1, lwd=5, col="black", xlab="Year", ylab="Cumulative Commitments (in Millions USD)", cex.axis=1.3, cex.lab=1.3, las=1, main="Transfers Over Time", cex.main=1.54, ylim=c(0,max(when.auts$huawei.cum/unit,when.dems$huawei.cum/unit)))
lines(when.dems$year, when.dems$huawei.cum/unit, lty=1, lwd=5, col="darkgray")
lines(when.dems.ins$year, when.dems.ins$huawei.cum/unit, lty=1, lwd=5, col="lightgray")
legend(x="topleft", legend=c("Autocracy","Democracy","Democracy (Excluding Indonesia)"), fill=c("black","darkgray","lightgray"), border=c("black","darkgray","lightgray"), cex=1.3, box.col=NA, bg=NA, text.col="Black")


#################################
# 		Transfers Volume			#
#################################

who = ddply(dat[dat$year>=2000 & dat$year<=2021,], .(cabb, year), plyr::summarize, huawei=sum(china.huawei,na.rm=T)/1000000, v2x_polyarchy=mean(v2x_polyarchy,na.rm=T), autocracy=mean(autocracy,na.rm=T))
who$huawei[is.na(who$huawei)==T] <- 0 
who <- who[who$huawei>0,]

par(mar=c(bottom=4,left=4.1,top=1.5,right=0.5), xpd=F)
hist(who$huawei, breaks=250, freq=T, main="Transfer Volume", col="black", border="black", cex.axis=1.3, cex.main=1.3, cex.lab=1.3, xlab="Transfer Value (in Millions USD)", ylab="Frequency")


#########################################
# 		Leading Sectors by Project		#
#########################################

global <- read.csv("AidData_Project_Level.csv")[,-c(1)]
global <- global[,c("Recipient","Sector.Name","Amount..Constant.USD2017.")]

what = ddply(global, .(Sector.Name), plyr::summarize, amount=sum(Amount..Constant.USD2017.,na.rm=T)/1000000)
what <- what[order(what$amount, decreasing=T),]

doughnut <-
  function (x, labels = names(x), edges = 200, outer.radius = 0.8,
            inner.radius=0.6, text.size=1.0, clockwise = FALSE,
            init.angle = if (clockwise) 90 else 0, density = NULL,
            angle = 45, col = NULL, border = FALSE, lty = NULL,
            main = NULL, ...)
  {
    if (!is.numeric(x) || any(is.na(x) | x < 0))
      stop("'x' values must be positive.")
    if (is.null(labels))
      labels <- as.character(seq_along(x))
    else labels <- as.graphicsAnnot(labels)
    x <- c(0, cumsum(x)/sum(x))
    dx <- diff(x)
    nx <- length(dx)
    plot.new()
    pin <- par("pin")
    xlim <- ylim <- c(-1, 1)
    if (pin[1L] > pin[2L])
      xlim <- (pin[1L]/pin[2L]) * xlim
    else ylim <- (pin[2L]/pin[1L]) * ylim
    plot.window(xlim, ylim, "", asp = 1)
    if (is.null(col))
      col <- if (is.null(density))
        palette()
    else par("fg")
    col <- rep(col, length.out = nx)
    border <- rep(border, length.out = nx)
    lty <- rep(lty, length.out = nx)
    angle <- rep(angle, length.out = nx)
    density <- rep(density, length.out = nx)
    twopi <- if (clockwise)
      -2 * pi
    else 2 * pi
    t2xy <- function(t, radius) {
      t2p <- twopi * t + init.angle * pi/180
      list(x = radius * cos(t2p),
           y = radius * sin(t2p))
    }
    for (i in 1L:nx) {
      n <- max(2, floor(edges * dx[i]))
      P <- t2xy(seq.int(x[i], x[i + 1], length.out = n),
                outer.radius)
      polygon(c(P$x, 0), c(P$y, 0), density = density[i],
              angle = angle[i], border = border[i],
              col = col[i], lty = lty[i])
      Pout <- t2xy(mean(x[i + 0:1]), outer.radius)
      lab <- as.character(labels[i])
      if (!is.na(lab) && nzchar(lab)) {
        lines(c(1, 1.05) * Pout$x, c(1, 1.05) * Pout$y)
        text(1.1 * Pout$x, 1.1 * Pout$y, labels[i], cex=text.size,
             xpd = TRUE, adj = ifelse(Pout$x < 0, 1, 0),
             ...)
      }
      ## Add white disc          
      Pin <- t2xy(seq.int(0, 1, length.out = n*nx),
                  inner.radius)
      polygon(Pin$x, Pin$y, density = density[i],
              angle = angle[i], border = border[i],
              col = "white", lty = lty[i])
    }
    
    title(main = main, ...)
    invisible(NULL)
  }


store <- sort(table(global$Sector.Name), decreasing=T)
store <- store[store>0]
names(store) <- c("Communications", "Education", "Government & Civil Society", "Emergency Response", "Other Social Infrastructure", "Health", "Food Aid", "Energy", "Other Multisector", "Administrative Costs", "General Budget Support", "Industry, Mining & Construction", "Other Commodity Assistance", "Population Programs")

input <- store

new <- sort(input, decreasing=T)[c(1:6)]
input <- c(new, sum(input)-sum(new))
names(input) <- c(names(new), "Other")
input <- input / sum(input)

colors <- gray.colors(n=length(input), start=0.1, end=0.9, gamma=2.2, alpha=0.5, rev=FALSE)

par(mar=c(0,0,2,0))
doughnut(x=input, outer.radius=0.5, inner.radius=0.2, text.size=1.3, col=colors, border="white" , clockwise=T, init.angle=180, main="Leading Sectors (By Project)", cex.main=1.54)


#########################################
# 		Leading Sectors by Value			#
#########################################

what <- what[order(what$amount, decreasing=T),]
what$Sector.Name <- c("Communications", "Energy", "Other Social Infrastructure", "Education", "Emergency Response", "Administrative Costs", "Government & Civil Society", "Other Multisector", "Health", "Food Aid", "Industry, Mining & Construction", "General Budget Support",  "Other Commodity Assistance", "Population Programs")

input <- what[,2]
names(input) <- what[,1]

new <- sort(input, decreasing=T)[c(1:2)]
input <- c(new, sum(input)-sum(new))
names(input) <- c(names(new), "Other")
input <- input / sum(input)

colors <- gray.colors(n=length(input), start=0.1, end=0.9, gamma=2.2, alpha=0.5, rev=FALSE)

par(mar=c(0,0,2,0))
doughnut(x=input, outer.radius=0.5, inner.radius=0.2, text.size=1.3, col=colors, border="white" , clockwise=T, init.angle=180, main="Leading Sectors (By Value)", cex.main=1.54)


#########################################
# 		Leading Regions by Value			#
#########################################

who = ddply(dat[dat$year>=2000 & dat$year<=2021,], .(cabb, year), plyr::summarize, huawei=sum(china.huawei,na.rm=T), v2x_polyarchy=mean(v2x_polyarchy,na.rm=T), autocracy=mean(autocracy,na.rm=T))
who$huawei[is.na(who$huawei)==T] <- 0 
who <- who[who$huawei>0,]
who.cabb = ddply(who, .(autocracy,cabb), plyr::summarize, huawei=sum(huawei,na.rm=T)/1000000, v2x_polyarchy=mean(v2x_polyarchy,na.rm=T))

who.cabb$region <- NA
who.cabb$region[who.cabb$cabb=="INS"] <- "Asia"
who.cabb$region[who.cabb$cabb=="UZB"] <- "Asia"
who.cabb$region[who.cabb$cabb=="CAO"] <- "Africa"
who.cabb$region[who.cabb$cabb=="COS"] <- "Latin America"
who.cabb$region[who.cabb$cabb=="CHA"] <- "Africa"
who.cabb$region[who.cabb$cabb=="DRC"] <- "Africa"
who.cabb$region[who.cabb$cabb=="CDI"] <- "Africa"
who.cabb$region[who.cabb$cabb=="BOL"] <- "Latin America"
who.cabb$region[who.cabb$cabb=="ETH"] <- "Africa"
who.cabb$region[who.cabb$cabb=="TUN"] <- "Africa"
who.cabb$region[who.cabb$cabb=="BUI"] <- "Africa"
who.cabb$region[who.cabb$cabb=="UKR"] <- "Europe"
who.cabb$region[who.cabb$cabb=="MAW"] <- "Africa"
who.cabb$region[who.cabb$cabb=="MLD"] <- "Europe"
who.cabb$region[who.cabb$cabb=="PAK"] <- "Asia"
who.cabb$region[who.cabb$cabb=="ALG"] <- "Africa"
who.cabb$region[who.cabb$cabb=="ANG"] <- "Africa"
who.cabb$region[who.cabb$cabb=="VEN"] <- "Latin America"
who.cabb$region[who.cabb$cabb=="TAJ"] <- "Asia"
who.cabb$region[who.cabb$cabb=="GAM"] <- "Africa"
who.cabb$region[who.cabb$cabb=="GHA"] <- "Africa"
who.cabb$region[who.cabb$cabb=="GUI"] <- "Africa"
who.cabb$region[who.cabb$cabb=="RWA"] <- "Africa"
who.cabb$region[who.cabb$cabb=="DRV"] <- "Asia"
who.cabb$region[who.cabb$cabb=="MYA"] <- "Asia"
who.cabb$region[who.cabb$cabb=="UGA"] <- "Africa"
who.cabb$region[who.cabb$cabb=="URU"] <- "Latin America"
who.cabb$region[who.cabb$cabb=="NIG"] <- "Africa"
who.cabb$region[who.cabb$cabb=="BLR"] <- "Europe"
who.cabb$region[who.cabb$cabb=="CAM"] <- "Asia"
who.cabb$region[who.cabb$cabb=="YEM"] <- "Middle East"
who.cabb$region[who.cabb$cabb=="TAZ"] <- "Africa"
who.cabb$region[who.cabb$cabb=="LAO"] <- "Asia"
who.cabb$region[who.cabb$cabb=="COL"] <- "Latin America"
who.cabb$region[who.cabb$cabb=="PER"] <- "Latin America"
who.cabb$region[who.cabb$cabb=="NIR"] <- "Africa"
who.cabb$region[who.cabb$cabb=="BOT"] <- "Africa"
who.cabb$region[who.cabb$cabb=="COM"] <- "Africa"
who.cabb$region[who.cabb$cabb=="NAM"] <- "Africa"

who.region = ddply(who.cabb, .(region), plyr::summarize, huawei=sum(huawei,na.rm=T))

input <- who.region[,2]
names(input) <- who.region[,1]

new <- sort(input, decreasing=T)#[c(1:10)]
#input <- c(new, sum(input)-sum(new))
#names(input) <- c(names(new), "Other")
input <- new
input <- input / sum(input)

colors <- gray.colors(n=length(input), start=0.1, end=0.9, gamma=2.2, alpha=0.5, rev=FALSE)

par(mar=c(0,0,2,0))
doughnut(x=input, outer.radius=0.5, inner.radius=0.2, text.size=1.3, col=colors, border="white" , clockwise=T, init.angle=180, main="Leading Regions (By Value)", cex.main=1.54)

